package task

import (
	"go-task/common"
	"go-task/data"
	"net"
	"time"
)

type ConnTaskHandler struct {
}

func NewConnTaskHandler() *ConnTaskHandler {
	return &ConnTaskHandler{}
}

func (c *ConnTaskHandler) Handler(s *TaskServer, conn net.Conn, msgData *data.MsgData) {
	var connData data.ConnData
	common.ParseJson(msgData.Data, &connData)

	// 权限校验
	if !authCheck(&connData) {
		s.authFail(conn)
		err := conn.Close()
		if err != nil {
			s.log.Errorf("conn auth handler err:%v", err)
			return
		}
		return
	}

	// 清除超时限制
	err := conn.SetReadDeadline(time.Time{})
	if err != nil {
		s.log.Errorf("conn set read deadline err:%v", err)
		return
	}

	s.authLock.Lock()
	s.authMap[conn] = true
	s.authLock.Unlock()

	clientData := &ClientData{
		Name: connData.Name,
		Conn: conn,
	}

	s.lock.Lock()
	s.connMap[conn] = connData.TaskGroup
	taskClient, ok := s.taskMap[connData.TaskGroup]
	if ok {
		if taskClient == nil {
			taskClient = &TaskClient{
				CurrentIndex: 0,
				Clients:      []*ClientData{clientData},
			}
			s.taskMap[connData.TaskGroup] = taskClient
		} else {
			taskClient.Clients = append(taskClient.Clients, clientData)
			s.taskMap[connData.TaskGroup] = taskClient
		}
	} else {
		taskClient = &TaskClient{
			CurrentIndex: 0,
			Clients:      []*ClientData{clientData},
		}
		s.taskMap[connData.TaskGroup] = taskClient
	}

	s.lock.Unlock()
	resp := data.MsgData{
		Action: data.CONN,
		Data:   "connected",
	}
	s.sendData(conn, common.JsonBytes(resp))
}

func authCheck(connData *data.ConnData) bool {
	taskConfig := common.Config.Task
	if taskConfig.Username != connData.Username {
		return false
	}
	if taskConfig.Password != connData.Password {
		return false
	}
	return true
}
